/**
 * copy aisc-i18n的源码，直接修改 _translations 和 _locale 写死
 */

import Mustache from 'mustache';
import formatMissingTranslation from './formatMissingTranslation';
import BaseComponent from './base';
import localeData from 'utils/locale.json';

const handleMissingTranslation = formatMissingTranslation;

export default {
  _localeKey: 'en-us',
  _translationsObject: {},
  _getTranslations: null,
  _getLocale: null,
  _handleMissingTranslation: handleMissingTranslation,
  _translations: localeData,
  _locale: 'zh-cn',

  setHandleMissingTranslation(fn) {
    if (typeof fn !== 'function') {
      throw new Error('Handle missing translation must be a function');
    }
    this._handleMissingTranslation = fn;
  },

  t(key, replacements = {}) {
    return this._translate(key, replacements);
  },

  _replace(translation, replacements) {
    return Mustache.render(translation, replacements);
  },

  _translate(key, replacements = {}) {
    let translation = '';
    try {
      const translationLocale = this._translations[this._locale]
        ? this._locale
        : this._locale.split('-')[0];
      translation = this._fetchTranslation(
        this._translations,
        `${translationLocale}.${key}`,
        replacements.count,
      );
    } catch (err) {
      return this._handleMissingTranslation(key, replacements);
    }
    return this._replace(translation, replacements);
  },

  _fetchTranslation(translations, key, count = null) {
    const _index = key.indexOf('.');
    if (typeof translations === 'undefined') {
      throw new Error('not found');
    }
    if (translations[key]) {
      return translations[key];
    }
    if (_index > -1) {
      return this._fetchTranslation(
        translations[key.substring(0, _index)],
        key.substr(_index + 1),
        count,
      );
    }
    if (count !== null) {
      if (translations[`${key}_${count}`]) {
        // when key = 'items_3' if count is 3
        return translations[`${key}_${count}`];
      }
      if (count !== 1 && translations[`${key}_plural`]) {
        // when count is not simply singular, return _plural
        return translations[`${key}_plural`];
      }
    }
    throw new Error('not found');
  },

  forceComponentsUpdate() {
    BaseComponent.rerenderAll();
  },
};
